package com.example.myblog.service;

import com.example.myblog.model.Category;
import com.example.myblog.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分类服务类
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;
    
    /**
     * 获取所有分类（按显示顺序排序）
     */
    public List<Category> getAllCategories() {
        return categoryRepository.findAllByOrderByDisplayOrderAsc();
    }
    
    /**
     * 根据ID获取分类
     */
    public Category getCategoryById(Long id) {
        return categoryRepository.findById(id).orElse(null);
    }
    
    /**
     * 根据名称获取分类
     */
    public Category getCategoryByName(String name) {
        return categoryRepository.findByName(name);
    }
    
    /**
     * 创建或更新分类
     */
    public Category saveCategory(Category category) {
        return categoryRepository.save(category);
    }
    
    /**
     * 删除分类
     */
    public void deleteCategory(Long id) {
        categoryRepository.deleteById(id);
    }
    
    /**
     * 更新分类显示顺序
     * @param categoryId 分类ID
     * @param displayOrder 显示顺序
     */
    @Transactional
    public void updateCategoryDisplayOrder(Long categoryId, int displayOrder) {
        Category category = getCategoryById(categoryId);
        if (category != null) {
            category.setDisplayOrder(displayOrder);
            saveCategory(category);
        }
    }
}